package test

import (
	"fmt"
	"github.com/go-redis/redis"
	"strconv"
	"time"
)

//Golang：通过Redis消息订阅实现key过期通知

func subs() {

	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "123456", // 如果没有设置密码，则为空字符串
		DB:       0,        // 使用默认数据库
	})

	defer client.Close()

	// 修改配置,开启事件监听 ps: 修改配置文件,效果等同
	_, err := client.ConfigSet("notify-keyspace-events", "Ex").Result()
	if err != nil {
		panic(err)
	}
	for i := 0; i < 10000; i++ {
		var s = `{ "act": "toUid","type": "chat","msg": {"id":"` + strconv.Itoa(i) + `","uid": "2","msg": "我很好","touid": "1"}}`
		// 设置key，并设置过期时间为10秒
		err = client.Set(s, "myvalue", 1*time.Second).Err()
		if err != nil {
			panic(err)
		}
	}

	//订阅
	pubsub := client.Subscribe("__keyevent@0__:expired")
	defer pubsub.Close()

	// 开启goroutine，接收过期事件
	go func() {
		for msg := range pubsub.Channel() {
			// 处理过期事件
			fmt.Println("Key expired:", msg.Payload)
		}
	}()
	select {} //阻塞主进程

}
func main() {
	subs()
}
